import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { message } from 'antd';
import { SingelUserType, IndexModelState } from './data.d';

import {
  getUserListService,
  saveUserService,
  deleteUserService,
  addUserService,
} from './service';

export interface IndexModelType {
  namespace: 'users';
  //state 是接口获取的数据格式，可以根据后端接口定义自定义state结构方便使用。相当于把返回json对象化。
  state: IndexModelState;
  effects: {
    getRemoteUserList: Effect;
    saveUser: Effect;
    deleteUser: Effect;
    addUser: Effect;
  };
  reducers: {
    getList: Reducer<IndexModelState>;
  };
  subscriptions: {
    setup: Subscription;
  };
}

const IndexModel: IndexModelType = {
  namespace: 'users',

  state: {
    data: [],
    meta: {
      total: 0,
      per_page: 10,
      page: 1,
    },
  },

  reducers: {
    getList(state, { payload }) {
      return payload;
    },
  },

  effects: {
    *getRemoteUserList(action, { put, call }) {
      const users = yield call(getUserListService);
      if (users) {
        yield put({
          type: 'getList',
          //此次必须用大括号套一层，view层通过.data访问数据，否则有问题。
          //原因原始data可能不止一个json节点 可能是数组所以必须二次拆封
          payload: { users },
        });
        message.success('数据获取成功！');
      } else {
        message.error('数据获取失败！');
      }
    },
    *saveUser({ payload: { id, value } }, { put, call }) {
      //call 多参数通过 {}处理
      const rs = yield call(saveUserService, { id, value });
      if (rs) {
        message.success('保存成功！');
        //可以put effect
        yield put({
          type: 'getRemoteUserList',
        });
      } else {
        message.error('保存失败！');
      }
    },
    *addUser({ payload }, { put, call }) {
      //call 多参数通过 {}处理
      const rs = yield call(addUserService, payload);
      //可以put effect
      if (rs) {
        message.success('添加成功！');
        yield put({
          type: 'getRemoteUserList',
        });
      } else {
        message.error('添加失败！');
      }
    },
    *deleteUser({ payload }, { put, call }) {
      const rs = yield call(deleteUserService, payload);
      if (rs) {
        message.success('删除成功！');
        yield put({
          type: 'getRemoteUserList',
        });
      } else {
        message.error('删除失败！');
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/users') {
          dispatch({
            type: 'getRemoteUserList',
          });
        }
      });
    },
  },
};

export default IndexModel;
